<template>
  <div class="app-container" v-hasPermi="['fang:maintenance:query']">
    <!-- 维修详情对话框 -->
    <el-dialog v-model="open" width="800px">
      <template #header>
        <div class="dialog-title">
          <span>维修详情-</span>
          <span v-if="detail.maintenanceStatus === MAINTENANCE_STATUS.REPAIR" class="status-in-progress">维修中</span>
          <span v-else-if="detail.maintenanceStatus === MAINTENANCE_STATUS.COMPLETED"
            class="status-completed">维修完成</span>
          <span v-else-if="detail.maintenanceStatus === MAINTENANCE_STATUS.PENDING" class="status-pending">待处理</span>
          <span v-else-if="detail.maintenanceStatus === MAINTENANCE_STATUS.DETERMINED"
            class="status-determined">待确认</span>
          <span v-else>维修详情</span>
        </div>
      </template>
      <!-- 报修信息部分 -->
      <div class="maintenance-info-section">
        <div class="section-title">报修信息</div>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">报修时间：</span>
            <span class="value">{{ detail.repairCreateTime ? parseTime(detail.repairCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') :
              '-'
              }}</span>
          </div>
          <div class="info-item">
            <span class="label">租客：</span>
            <span class="value">{{ detail.tenantUserName || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">电话：</span>
            <span class="value">{{ detail.tenantUserPhone || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">房源信息：</span>
            <span class="value">{{ detail.address || '-' }}</span>
          </div>
        </div>
        <div class="description-section">
          <div class="info-item">
            <span class="label">简要描述：</span>
            <span class="value">{{ detail.simpleDescription || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">详细描述：</span>
            <span class="value">{{ detail.detailDescription || '-' }}</span>
          </div>
        </div>
        <div class="attachment-section">
          <span class="label">附件：</span>
          <div class="attachment-preview-inline" v-if="detail.descriptionPicFileList?.length > 0">
            <div v-for="(file, index) in detail.descriptionPicFileList" :key="index" class="attachment-item-small">
              <el-image :src="file.url" :preview-src-list="detail.descriptionPicFileList.map(f => f.url)"
                :initial-index="index" fit="cover" class="attachment-image-small" />
            </div>
          </div>
          <div v-else class="no-attachment">暂无附件</div>
        </div>
      </div>

      <!-- 维修进程部分 -->
      <div class="maintenance-progress-section">
        <div class="section-title">维修进程</div>

        <el-steps direction="vertical" :active="detail.nodeList?.length || 0" finish-status="success">
          <!-- 历史维修进程 -->
          <el-step v-for="(item, index) in (detail.nodeList || [])" :key="index">
            <template #title>
              <div class="step-title">
                <span class="step-description-text">阶段备注：{{ item.simpleDescription || '-' }}</span>
                <span class="step-time-small">{{ item.maintenanceUpdateTime ? parseTime(item.maintenanceUpdateTime,
                  '{y}-{m}-{d} {h}:{i}:{s}') : '-' }}</span>
              </div>
            </template>
            <template #description>
              <div class="step-content">
                <div class="step-attachments-inline" v-if="item.descriptionPicFileList?.length > 0">
                  <span class="label">附件：</span>
                  <div class="attachment-preview-inline">
                    <div v-for="(file, fileIndex) in item.descriptionPicFileList" :key="fileIndex"
                      class="attachment-item-small">
                      <el-image :src="file.url" :preview-src-list="item.descriptionPicFileList.map(f => f.url)"
                        :initial-index="fileIndex" fit="cover" class="attachment-image-small" />
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-step>

          <!-- 当前可编辑阶段 -->
          <el-step title="当前阶段" status="process" v-if="isMaintenanceEditableStatus(detail.maintenanceStatus)" v-hasPermi="['fang:maintenance:addnode']">
            <template #description>
              <div class="step-content current-step">
                <el-form ref="currentStepFormRef" :model="addNodeParam" :rules="rules" label-width="80px">
                  <div class="step-description">
                    <span class="label">阶段备注：</span>
                    <el-input v-model="addNodeParam.simpleDescription" v-trim placeholder="管理员备注...." clearable
                      class="admin-input" />
                  </div>
                  <div class="step-attachments-inline">
                    <span class="label">附件：</span>
                    <ImageUpload v-model="addNodeParam.descriptionPicFileList" :limit="5" />
                  </div>
                  <div class="add-stage-button">
                    <el-button type="primary" @click="addNode">
                      新增维修阶段
                    </el-button>
                  </div>
                </el-form>
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <template v-show="isMaintenanceEditableStatus(detail.maintenanceStatus)">
            <el-button type="primary" @click="submitForm" v-hasPermi="['fang:maintenance:complete']">
              维修完成
            </el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MaintenanceDetial">
import { getMaintenance, addMaintenanceNode, completeMaintenanceNode } from "@/api/fang/maintenance"
import ImageUpload from '@/components/ImageUpload/index.vue'
import { MAINTENANCE_STATUS, MAINTENANCE_STATUS_TEXT, MAINTENANCE_STATUS_COLOR, isMaintenanceEditableStatus, isMaintenanceCompletedStatus } from '@/utils/enums'
import { nextTick } from 'vue'


const handleFrontSuccess = (file) => {
  console.log('正面照片上传成功', file);
  // 这里添加实际的上传逻辑
};

const { proxy } = getCurrentInstance()

const open = ref(false)
const detail = ref({}) // 只读详情信息
const addNodeParam = ref({
  descriptionPicFileList: [],
  simpleDescription: ""
})
const rules = ref({})

defineExpose({ openDetailDialog });


// 取消按钮
function cancel() {
  open.value = false
}


// 表单重置
function reset() {
  detail.value = {}
}

function resetaddNodeParam() {
  addNodeParam.value = {
    descriptionPicFileList: [],
    simpleDescription: ""
  }
}



function openDetailDialog(dataId) {
  // 先关闭弹窗，确保状态干净
  open.value = false

  // 重置数据
  reset()
  resetaddNodeParam()

  const _id = dataId
  getMaintenance(_id).then(response => {
    detail.value = response.data
    // 直接打开弹窗，不使用nextTick
    open.value = true
  })
}


/** 提交按钮 */
function submitForm() {

  const nodeLista = addNodeParam.value.descriptionPicFileList; // 获取数组 

  const addnodefileList = []
  for (let i = 0; i < nodeLista.length; i++) {
    console.log(nodeLista[i].url);
    addnodefileList.push({ 'id': nodeLista[i].id, "url": nodeLista[i].url })
  }

  const dateAddNode = {
    "simpleDescription": addNodeParam.value.simpleDescription,
    "maintenanceId": detail.value.id,
    "descriptionPicFileList": addnodefileList
  }
  completeMaintenanceNode(dateAddNode).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    // 直接重新打开弹窗，不关闭
    openDetailDialog(detail.value.id)
  })

  // proxy.$refs["maintenanceRef"].validate(valid => {
  //   if (valid) {
  //     if (form.value.id != null) {
  //       updateMaintenance(form.value).then(response => {
  //         proxy.$modal.msgSuccess("修改成功")
  //         open.value = false
  //         //tod 刷新列表
  //         //getList()
  //       })
  //     } else {
  //       addMaintenance(form.value).then(response => {
  //         proxy.$modal.msgSuccess("新增成功")
  //         open.value = false
  //         //getList()//tod 刷新列表
  //       })
  //     }
  //   }
  // })
}

/** 新增维修节点 */
function addNode() {
  if (!addNodeParam.value.simpleDescription.trim()) {
    proxy.$modal.msgError("请输入阶段备注")
    return
  }

  const nodeLista = addNodeParam.value.descriptionPicFileList; // 获取数组 

  const addnodefileList = []
  for (let i = 0; i < nodeLista.length; i++) {
    console.log(nodeLista[i].url);
    addnodefileList.push({ 'id': nodeLista[i].id, "url": nodeLista[i].url })
  }

  const dateAddNode = {
    "simpleDescription": addNodeParam.value.simpleDescription,
    "maintenanceId": detail.value.id,
    "descriptionPicFileList": addnodefileList
  }
  addMaintenanceNode(dateAddNode).then(response => {
    proxy.$modal.msgSuccess("新增维修阶段成功")
    // 直接重新打开弹窗，不关闭
    openDetailDialog(detail.value.id)
  })
}



//getList()
</script>

<style lang="scss" scoped>
.maintenance-info-section,
.maintenance-progress-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0 15px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  // min-width: 100px;
  margin-right: 10px;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

.description-section {
  margin-bottom: 15px;
}

.attachment-section {
  margin-top: 10px;
}

.attachment-section .label {
  font-weight: 500;
  color: #606266;
  margin-right: 10px;
}

.attachment-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.attachment-preview-inline {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-left: 8px;
}

.attachment-item {
  width: 80px;
  height: 80px;
  /* border: 1px dashed #d9d9d9; */
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
}

.attachment-item-small {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.attachment-image {
  width: 100%;
  height: 100%;
  border-radius: 6px;
}

.attachment-image-small {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.no-attachment {
  color: #909399;
  font-style: italic;
}

.step-title {
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

.step-description-text {
  font-weight: 500;
  color: #303133;
}

.step-time-small {
  font-size: 12px;
  color: #909399;
}

.step-content {
  padding: 10px 0;
}

.step-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.step-description {
  margin-bottom: 10px;
}

.step-description .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.step-description .value {
  color: #303133;
}

.step-attachments {
  margin-top: 10px;
}

.step-attachments .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.step-attachments-inline {
  display: flex;
  align-items: flex-start;
  margin-top: 8px;
}

.step-attachments-inline .label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  white-space: nowrap;
  align-self: flex-start;
  padding-top: 0;
}

.current-step {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin-top: 10px;

  .step-attachments-inline .label {
    width: 60px;
  }

  .step-description .label {
    width: 60px;
  }
}

.admin-input {
  width: 300px;
}

.add-stage-button {
  margin-top: 15px;
}


.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* ImageUpload 组件样式调整 */
:deep(.el-upload--picture-card) {
  width: 60px;
  height: 60px;
  line-height: 60px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 60px;
  height: 60px;
}

/* 确保ImageUpload组件与附件预览对齐 */
:deep(.component-upload-image) {
  display: inline-block;
  vertical-align: top;
}

:deep(.component-upload-image .el-upload-list) {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 0;
  padding: 0;
  align-items: flex-start;
}

:deep(.component-upload-image .el-upload) {
  vertical-align: top;
}

/* 弹窗标题样式 */
.dialog-title {
  font-size: 18px;
  font-weight: 500;
}

.status-pending {
  color: #909399;
  font-weight: 600;
}

.status-in-progress {
  color: #409EFF;
  font-weight: 600;
}

.status-determined {
  color: #E6A23C;
  font-weight: 600;
}

.status-completed {
  color: #67C23A;
  font-weight: 600;
}
</style>